import EventCenter from "../../lib/EventCenter";
import GameCfgData from "../../lib/GameCfgData";
import MathTool from "../../lib/MathTool";
import MyDialogManager from "../../lib/MyDialogManager";
import Sdk from "../../lib/Sdk";
import SoundManager from "../../lib/SoundManger";
import { TipManager } from "../../lib/TipManager";

import { ui } from "../../ui/layaMaxUI";
import AnimManager from "../AnimManager";
import EventEunm from "../data/EventEunm";
import ItemBaseData from "../data/ItemBaseData";
import PlayerData from "../data/PlayerData";
import Grid from "../Grid";
import GridManager from "../GridManager";
import CircleCdSpScript from "../scripts/CircleCdSpScript";
import PaoFireCtr from "../scripts/PaoFireCtr";
import DaoJuCtr from "../view/DaoJuCtr";
import Item from "../view/Item";
export default class GameScene extends ui.GameSceneUI {
    private mPaoPos: Laya.Point = new Laya.Point();
    private mdaojus: Array<ItemBaseData>
    private mMinX: number = 30;
    private mMaxX: number = 690;
    /**0初始化 1准备完毕 3任务达成 4无尽模式升级中 5无尽奖励掉落中或障碍生成中*/
    private gameSt: number = 0;
    private canFire: boolean;
    private mCanFire2: boolean;
    private mlineData;
    private mPaoCtr: PaoFireCtr;
    private mSelectItems: Array<Item>
    private mFirePos: Laya.Point;
    private mDaoJUCtr: DaoJuCtr;
    private mDaoJuCtrs: Array<DaoJuCtr>
    private mDaoJuIndex: number = 0;
    private mUnlockDaoJuIndex: number = 0;
    private mIsFlying: boolean;
    private mIsMouseDown: boolean;
    private mIsGameOver = false;
    private mHaveRevive: boolean = false;
    private mIsWuJin: boolean;
    private mWuJinRandomAddItems = [1003, 1004, 1005, 1011];
    private mWuJinUpDaoJuAddItems = [1008, 1009, 1012];//1013
    private mFireIndex: number = 0;
    private mAddRandomDaojuIndex: number = 0;
    private mMaxRandomDaojuIndex: number = 8;

    private mSelectData: ItemBaseData;
    private mSelectIndex: number = -1;
    private mDaojuImg: Item = new Item();
    constructor() {
        super();
        this.mdaojus = [new ItemBaseData(100004), new ItemBaseData(100005), new ItemBaseData(100006)]
        this.mPaoCtr = new PaoFireCtr(this.fireSp);
        this.mDaoJUCtr = new DaoJuCtr(this.buttomSp.getChildByName("d0"), 0);
        this.mDaoJuCtrs = [];
        let tdaojuctr: DaoJuCtr;
        for (let i = 1; i <= 3; i++) {
            tdaojuctr = new DaoJuCtr(this.buttomSp.getChildByName("d" + i), i);
            tdaojuctr.setData(this.getDaoJuData(i), 1);
            this.mDaoJuCtrs.push(tdaojuctr);
        }
    }

    onOpened(_isWuJi: boolean) {
        this.height = this.bg.height = Laya.stage.height;
        this.flashImg.height = Laya.stage.height;
        this.mIsWuJin = _isWuJi;
        this.mUnlockDaoJuIndex = 0;

        this.mAddRandomDaojuIndex = 0;
        this.mPaoCtr.show(false);
        // if(PlayerData.getIns().currGate>=this.mdaojus[2].unlockLevel)this.mUnlockDaoJuIndex=2;
        // else if(PlayerData.getIns().currGate>=this.mdaojus[1].unlockLevel)this.mUnlockDaoJuIndex=1;
        let tgate = PlayerData.getIns().currGate;
        //tgate=70;
        let tdata = _isWuJi ? null : GameCfgData.getIns().getGateCfg(tgate);
        GridManager.getIns().initData(tdata, this.itemParent, this, _isWuJi);
        if (!_isWuJi) {

            this.mPaoCtr.setPaoNum(GridManager.getIns().gateData.step);
        } else {
            this.updateWuJinTask();
            this.mPaoCtr.setPaoNum(100, true);
        }
        let tshouguid = false;
        if (tgate == 1) tshouguid = true;
        this.showGuid(tshouguid);
        this.taskSp.visible = !_isWuJi;
        this.wujinSp.visible = _isWuJi;
        this.mPaoPos.setTo(this.fireSp.x + 80 - this.mMinX, this.fireSp.y);
        this.mFirePos = this.itemParent.globalToLocal(new Laya.Point(this.fireSp.x + 80, this.fireSp.y));

        this.lineImg.visible = this.mIsWuJin;

        this.mDaoJuIndex = 0;
        let tislunck = PlayerData.getIns().currGate >= 5;
        this.mDaoJUCtr.show(tislunck);
        if (tislunck) {
            // if(_isWuJi)this.mDaoJUCtr.setData(new ItemBaseData(10007));
            // else this.mDaoJUCtr.setData(this.mdaojus[this.mDaoJuIndex]);
            this.mDaoJUCtr.setData(this.mdaojus[this.mDaoJuIndex], 0, this.mIsWuJin);
        }


        this.mHaveRevive = false;
        this.canFire = true;
        this.mCanFire2 = true;
        this.addEvent();
        EventCenter.getIns().event(EventEunm.taskChange);
        SoundManager.playMiuse("bg1.mp3");
        Laya.timer.once(1000, this, () => {
            this.mPaoCtr.show(true);
            this.changeGameSt(1);
            if (!this.mIsWuJin) GridManager.getIns().checkItemParentPos();
        });
        if (Sdk.getIns().isLongScene) {
            Sdk.getIns().showBanner();
        }
    }

    private addEvent() {
        this.settingBtn.on(Laya.Event.CLICK, this, this.settingClick);
        this.settingView.getChildByName("settingMainView").getChildByName("soundBtn").on(Laya.Event.CLICK, this, this.soundClick);
        this.settingView.getChildByName("settingMainView").getChildByName("musicBtn").on(Laya.Event.CLICK, this, this.musicClick);
        this.settingView.getChildByName("settingMainView").getChildByName("homeBtn").on(Laya.Event.CLICK, this, this.homeClick);
        this.on(Laya.Event.MOUSE_DOWN, this, this.mousedownHandler);
        this.on(Laya.Event.MOUSE_UP, this, this.mouseUpHandler);
        this.on(Laya.Event.MOUSE_OUT, this, this.mouseoutHandler);
        EventCenter.getIns().on(EventEunm.restgame, this, this.rest);
        EventCenter.getIns().on(EventEunm.revive, this, this.revive);
        EventCenter.getIns().on(EventEunm.itemChange, this, this.freshDaoJu);
        EventCenter.getIns().on(EventEunm.daojuMax, this, this.daojuMax);
        EventCenter.getIns().on(EventEunm.canceUseDaoJu, this, this.canceUseDaoJu);
        EventCenter.getIns().on(EventEunm.mouseEnableChange, this, this.mouseEnableChange);

        this.mDaoJUCtr.setClickFunc(this.useItemClick, this);
        for (let i = 0; i < this.mDaoJuCtrs.length; i++) {
            this.mDaoJuCtrs[i].setClickFunc(this.useItemClick, this);
        }
        this.timer.loop(1000, this, this.update);
    }
    private removeEvent() {
        this.settingBtn.off(Laya.Event.CLICK, this, this.settingClick);
        this.settingView.getChildByName("settingMainView").getChildByName("soundBtn").off(Laya.Event.CLICK, this, this.soundClick);
        this.settingView.getChildByName("settingMainView").getChildByName("musicBtn").off(Laya.Event.CLICK, this, this.musicClick);
        this.settingView.getChildByName("settingMainView").getChildByName("homeBtn").off(Laya.Event.CLICK, this, this.homeClick);
        this.off(Laya.Event.MOUSE_DOWN, this, this.mousedownHandler);
        this.off(Laya.Event.MOUSE_UP, this, this.mouseUpHandler);
        this.off(Laya.Event.MOUSE_OUT, this, this.mouseoutHandler);
        EventCenter.getIns().off(EventEunm.restgame, this, this.rest);
        EventCenter.getIns().off(EventEunm.revive, this, this.revive);
        EventCenter.getIns().off(EventEunm.itemChange, this, this.freshDaoJu)
        EventCenter.getIns().off(EventEunm.daojuMax, this, this.daojuMax);
        EventCenter.getIns().off(EventEunm.canceUseDaoJu, this, this.canceUseDaoJu);
        EventCenter.getIns().off(EventEunm.mouseEnableChange, this, this.mouseEnableChange);

        this.timer.clear(this, this.update);
    }

    private update() {
        if (this.gameSt != 1) return;
        if (GridManager.getIns().isMoving) return;
        this.checkGameOver();
        if (this.mIsWuJin) {
            if (GridManager.getIns().isEmpty) {
                this.hardLvUp();
                return;
            }
            if (this.canFire && !this.mIsFlying) GridManager.getIns().checkRowAdd();
        } else {
            if (this.canFire && !this.mIsFlying) GridManager.getIns().checkItemParentPos();
        }
    }

    private inGameSt() {
        return this.gameSt == 1;
    }
    private changeGameSt(_st: number) {
        this.gameSt = _st;
    }

    private updateWuJinTask() {
        this.wujinSp.getChildByName("scoreTxt")["text"] = GridManager.getIns().score;
        this.wujinSp.getChildByName("hscoreTxt")["text"] = PlayerData.getIns().hisScore;
        this.wujinSp.getChildByName("cdSp").getComponent(CircleCdSpScript).drawByPorss(GridManager.getIns().getDaojuPross(2));
    }

    private showGuid(_vale: boolean) {
        this.fireSp.getChildByName("guid")["visible"] = _vale;
    }

    private freshDaoJu() {
        for (let i = 0; i < this.mDaoJuCtrs.length; i++) {
            this.mDaoJuCtrs[i].fresh();
        }
    }

    private daojuMax() {

        let tpross: number;
        tpross = GridManager.getIns().getDaojuPross();
        this.mDaoJUCtr.setPross(tpross);
        // if(this.mIsWuJin){
        //     tpross = GridManager.getIns().getDaojuPross(2);
        // }else{
        // }
        if (this.mIsWuJin) this.updateWuJinTask();
    }


    private settingClick(e: Laya.Event) {
        e.stopPropagation();
        this.settingView.getChildByName("settingMainView")["visible"] = !this.settingView.getChildByName("settingMainView")["visible"]
        if (this.settingView.getChildByName("settingMainView")["visible"]) {
            this.freshSettingView();
        }
    }

    private soundClick() {
        SoundManager.soundMute = !SoundManager.soundMute;
        this.freshSettingView();
    }

    private musicClick() {
        SoundManager.musicMute = !SoundManager.musicMute;
        this.freshSettingView();
    }

    private homeClick() {
        this.settingView.getChildByName("settingMainView")["visible"] = false;
        MyDialogManager.getIns().sceneOpen("QuitDialog.scene");
    }

    private mousedownHandler() {
        if (this.mPaoCtr.paoNum <= 0) return;
        if (this.settingView.getChildByName("settingMainView")["visible"]) return;
        if (!this.canClick()) return;
        this.on(Laya.Event.MOUSE_MOVE, this, this.moveHandler);
        this.mIsMouseDown = true;
    }

    private mouseUpHandler(e: Laya.Event) {
        this.off(Laya.Event.MOUSE_MOVE, this, this.moveHandler);

        if (this.canClick() && this.mIsMouseDown) {
            if (e.stageY < this.mPaoPos.y - 40) {

                if (this.canFire) {
                    if (this.mSelectData) {
                        if (this.mSelectData.isDisposeConnectProp) {
                            this.addItem(this.mSelectData);
                            this.nextDaoju();
                            GridManager.getIns().restDaojuStep();
                        } else {

                            this.useItem(this.mSelectData, e.stageX, e.stageY);
                            GridManager.getIns().addScore(2000);
                        }
                    } else {
                        if (this.mlineData) {
                            let titemdata: ItemBaseData = this.mPaoCtr.fire();
                            if (titemdata) {
                                if (titemdata.isCanMove) {
                                    this.addItem(titemdata);
                                }
                            }
                        }
                    }
                }
               
            } else {
                this.mlineData = null;

            }

            this.clear();
        } else if (this.gameSt == 2) {

        }
        this.canFire = true;
        this.mIsMouseDown = false;
    }

    /**检测是否创建随机障碍或奖励*/
    private checkAdd(){
        if (this.mIsWuJin) {
            if(GridManager.getIns().isEmpty)return;
            this.mAddRandomDaojuIndex++;

            if (this.mAddRandomDaojuIndex >= this.mMaxRandomDaojuIndex) {
                this.mAddRandomDaojuIndex = 0;
                this.addRandomItems();
            }
            if (GridManager.getIns().currDaojuStep2 >= GridManager.getIns().maxDaojuStep2) {

                this.createSpItem();
            }
        }
    }

    private mouseoutHandler() {
        this.off(Laya.Event.MOUSE_MOVE, this, this.moveHandler);
        if (!this.canClick()) return;
        this.mlineData = null;
        this.clear();
        this.mIsMouseDown = false;
    }

    private moveHandler(e: Laya.Event) {
        if (!this.canClick()) return;
        if(!this.mIsMouseDown)return;
        if (e.stageY < this.mPaoPos.y - 40) {
            if (this.gameSt == 1) {
                if (this.mPaoCtr.currData) {
                    this.mlineData = this.createLineData(e.stageX - this.mMinX, e.stageY - this.lineSp.y);
                    if (this.mSelectData) {
                        if (this.mSelectData.isBombProp || this.mSelectData.isBigBombProp) {
                            let tp = this.mlineData.points[this.mlineData.points.length - 1];
                            this.setSelectItems(this.mSelectData, tp.x, tp.y);
                        } else if (this.mSelectData.isLineProp) {
                            this.setSelectItems(this.mSelectData, e.stageX, e.stageY);
                        }
                    }
                    let tpoints = this.mlineData.linePoints;
                    this.drawLine(tpoints);
                    let tangle = this.mlineData.angle; //MathTool.getAngleByTwoPoint(this.mPaoPos.x,this.mPaoPos.y,e.stageX-this.mMinX,e.stageY);
                    this.dirSp.rotation = tangle + 90;

                }
                this.canFire = true;
            }
        } else {
            this.clear();

        }
    }

    private freshSettingView() {
        this.settingView.getChildByName("settingMainView").getChildByName("soundBtn").getChildByName("x")["visible"] = SoundManager.soundMute;
        this.settingView.getChildByName("settingMainView").getChildByName("musicBtn").getChildByName("icon")["texture"] = SoundManager.musicMute ? "main/s12.png" : "main/s9.png";
        let tasksp = this.settingView.getChildByName("settingMainView").getChildByName("taskSp");
        if (this.mIsWuJin) {

        } else {

            tasksp.getChildByName("gateTxt")["text"] = GridManager.getIns().gateData.getGateName();
            tasksp.getChildByName("tipTxt")["text"] = GridManager.getIns().gateData.getTaskDes();
            tasksp.getChildByName("icon")["skin"] = GridManager.getIns().gateData.getTaskIcon();
        }
    }

    private addItem(_data: ItemBaseData) {
        let trc = this.mlineData.rc;
        if (trc) {
            //console.log("addItem",this.mlineData);
            if (!this.mlineData.points2.length) {
                console.log("addItem err");
                return;
            }
            let tdata = _data.clone();
            let titem: Item = new Item(tdata);
            this.mPaoCtr.currData = null;
            this.mIsFlying = true;
            titem.setPos(this.mlineData.points2[0].x, this.mlineData.points2[0].y)//this.mFirePos.x,this.mFirePos.y);
            titem.isFire = true;
            this.itemParent.addChild(titem);
            titem.moveByPath(this.mlineData.points2, trc.row, trc.col, () => {
                titem.setRC(trc.row, trc.col);
                let ttime2: number = 2000;
                if (GridManager.getIns().grid.isInLimit(trc.row, trc.col) && !GridManager.getIns().grid.isUpOut(titem.x, titem.y)) {
                    GridManager.getIns().grid.addItem(titem);
                    let tdata = GridManager.getIns().flyOverCheck(titem);
                    let time = tdata.timeIndex * 500;
                    if (!tdata.find) {
                        SoundManager.playSound("dong.mp3");
                    }
                    Laya.timer.once(time, this, () => {
                        this.mIsFlying = false;
                        GridManager.getIns().checkDropItems();
                        this.checkAdd();
                    });
                    ttime2 += time;
                } else {

                    GridManager.getIns().removeItem(titem, false);
                    this.mIsFlying = false;
                    GridManager.getIns().checkDropItems();
                    this.checkAdd();
                }
                this.mPaoCtr.createNextData();
                this.mPaoCtr.change();
                this.mFireIndex++;
                if (this.mFireIndex >= 4 && this.mIsWuJin) {
                    GridManager.getIns().downRow();
                    this.mFireIndex = 0;
                }


                Laya.timer.clear(this, this.checkGameOver);
                Laya.timer.once(ttime2, this, this.checkGameOver, [true]);

            }, (_pos) => {
                if (this.mlineData.blister) {
                    let titem: Item;
                    for (let i = this.mlineData.blister.length - 1; i >= 0; i--) {
                        titem = this.mlineData.blister[i];
                        if (MathTool.getTwoPointDist(_pos.x, _pos.y, titem.x, titem.y) <= ItemBaseData.WIDTH) {
                            titem = this.mlineData.blister.splice(i, 1)[0];
                            GridManager.getIns().clearGridData(titem)
                            GridManager.getIns().removeItem(titem);
                        }
                    }
                }
            });
        }
    }

    private rest() {
        this.itemParent.removeChildren();
        let tdata = this.mIsWuJin ? null : GameCfgData.getIns().getGateCfg(PlayerData.getIns().currGate);
        GridManager.getIns().initData(tdata, this.itemParent, this, GridManager.getIns().isWuJiMode);
        if (!this.mIsWuJin) this.mPaoCtr.setPaoNum(GridManager.getIns().gateData.step);
        this.changeGameSt(1);
        this.mIsGameOver = false;
        this.mCanFire2 = true;
        this.mAddRandomDaojuIndex = 0;
        this.timer.loop(1000, this, this.update);

    }

    private revive() {
        this.mHaveRevive = true;
        this.changeGameSt(1);
        this.mIsGameOver = false;
        if (!this.mIsWuJin) this.mPaoCtr.addPaoNum(5);
        else GridManager.getIns().downRow(-200);
        this.timer.loop(1000, this, this.update);
    }

    private showFlashImg(_func: Function) {
        this.flashImg.visible = true;
        SoundManager.playSound("jingbao.mp3");
        Laya.timer.once(3000, this, () => {
            this.flashImg.visible = false;
            _func();
        });
    }

    private addRandomItems() {
        let tnum = GridManager.getIns().getHardLvObsNum();
        
        if (!this.mCanFire2) return;
        this.mCanFire2 = false;
        this.changeGameSt(5);
        this.showFlashImg(() => {
            let tp = this.itemParent.globalToLocal(this.mPaoPos, true);
            let trcs = this.getRandomRCs(6);
            let tpos;
            let tobs=0;
            let time: number;
            for (let i = 0; i < trcs.length; i++) {
                let titem: Item = new Item(new ItemBaseData(this.getWuAddItemId(tobs,tnum)));
                titem.pos(tp.x, tp.y);
                this.itemParent.addChild(titem);
                tpos = ItemBaseData.getPosByRC(trcs[i].row, trcs[i].col);
                time = MathTool.getTwoPointDist(tp.x, tp.y, tpos.x, tpos.y) * 2;
                Laya.Tween.to(titem, { x: tpos.x, y: tpos.y }, time, null, Laya.Handler.create(this, (_item: Item, _rc, _index: number) => {
                    _item.setRC(_rc.row, _rc.col);
                    let titem2 = GridManager.getIns().grid.getItem(_rc.row, _rc.col);
                    if (titem2) GridManager.getIns().grid.removeItem(titem2);
                    GridManager.getIns().grid.addItem(_item);
                    if (i == trcs.length - 1) {
                        this.mCanFire2 = true;
                        this.changeGameSt(1);
                    }
                }, [titem, trcs[i], i]));
            }
        });
    }

    private getWuAddItemId(obs:number=0,maxNum:number){
        if(obs>=maxNum){
            
        }
        let tid=this.mWuJinRandomAddItems[Math.floor(Math.random() * this.mWuJinRandomAddItems.length)];
        return tid;
    }

    private createSpItem() {
        if (!this.mCanFire2) return;
        this.mCanFire2 = false;
        this.changeGameSt(5);
        let timg: Laya.Image = this.wujinSp.getChildByName("icon") as Laya.Image;
        let tp: Laya.Point = new Laya.Point(360, 600);
        let trc = this.getRandomRCs(1)[0]
        if(!trc){
            this.mCanFire2 = true;
            this.changeGameSt(1);
            return;
        }
        let tpos = ItemBaseData.getPosByRC(trc.row, trc.col);
        Laya.Tween.to(timg, { x: tp.x, y: tp.y }, 1000, Laya.Ease.circInOut, Laya.Handler.create(this, () => {
            let titem = new Item(new ItemBaseData(this.mWuJinUpDaoJuAddItems[Math.floor(Math.random() * this.mWuJinUpDaoJuAddItems.length)]));
            AnimManager.show(this, tp.x, tp.y, AnimManager.BombSpAnim);
            this.itemParent.globalToLocal(tp);
            titem.pos(tp.x, tp.y);
            timg.pos(320, 14);
            this.itemParent.addChild(titem);
            Laya.Tween.to(titem, { x: tpos.x, y: tpos.y }, 1000, null, Laya.Handler.create(this, (_item, _rc) => {
                _item.setRC(_rc.row, _rc.col);
                let titem2 = GridManager.getIns().grid.getItem(_rc.row, _rc.col);
                if (titem2) GridManager.getIns().grid.removeItem(titem2);
                GridManager.getIns().grid.addItem(_item);
                this.mCanFire2 = true;
                this.changeGameSt(1);
            }, [titem, trc]), 500);
        }));
        GridManager.getIns().restDaojuStep2();
    }

    private gameOverSubItems(_num: number) {
        //console.log("gameOverSubItems",_num);
        let tids = [];
        GridManager.getIns().addScore(_num * 250);
        EventCenter.getIns().event(EventEunm.taskChange);
        for (let i = 1; i <= 5; i++) {
            tids.push(i + 5 * PlayerData.getIns().currItemType)
        }
        this.mPaoCtr.clearIcons();
        for (let i = 0; i < _num; i++) {
            let timg = Laya.Pool.getItemByClass("itemImg", Laya.Image);
            timg.anchorX = timg.anchorY = 0.5;
            timg.skin = GameCfgData.getIns().getItemIcon(tids[Math.floor(Math.random() * tids.length)]);
            timg.pos(360, this.mFirePos.y + 30);
            this.addChild(timg);
            Laya.timer.once(i * 50, this, () => {
                this.mPaoCtr.subPao();
                Laya.Tween.to(timg, { x: 360 + (-200 + Math.random() * 400), y: this.mFirePos.y - 200 }, 500, Laya.Ease.circOut, Laya.Handler.create(this, (_img: Laya.Image) => {
                    _img.removeSelf();
                    Laya.Pool.recover("itemImg", _img);
                }, [timg]))

            })
        }
    }



    private checkGameOver(_checkNum: boolean = false) {
        //if(this.mIsFlying)return;
        if (this.mIsWuJin) {

            if (GridManager.getIns().isWuJinOver()) {
                this.gameOver(false);

            }
        } else {
            if (GridManager.getIns().getTaskPross() >= 1) {
                this.changeGameSt(3);
                let time = 1000;
                let tnum = this.mPaoCtr.paoNum;
                time = tnum > 0 ? 1000 : 0;
                if (tnum > 0) this.gameOverSubItems(tnum);
                if (GridManager.getIns().gateData.task != 0) {
                    GridManager.getIns().dropAll();
                }
                Laya.timer.once(time, this, () => {
                    this.gameOver(true);

                })
            }
            if (_checkNum) {
                if (this.mPaoCtr.paoNum <= 0) {
                    this.gameOver(false);
                }
            }
        }
    }

    private useItemClick(_data: ItemBaseData, _id: number) {
        if (this.mSelectData) return;
        let tcanUse = false;
        if (_id == 0) {
            if (GridManager.getIns().getDaojuPross() >= 1) tcanUse = true;
        } else {
            if (PlayerData.getIns().haveEnghItem(_data.id + "", 1)) tcanUse = true;
        }
        if (tcanUse) {
            if (_data.isShowMoreProp) {
                if (this.mPaoCtr.posNum > 2) {
                    TipManager.ins.showMsgAlert("无法多次使用", this);
                } else {
                    PlayerData.getIns().addItem(_data.id + "", -1);
                    this.mDaoJuCtrs[1].fresh();
                    this.mPaoCtr.addPos(2);
                }
                return;
            }
            let tdata = _data;
            this.mSelectIndex = _id;
            this.mSelectData = tdata;
            this.mPaoCtr.setPropData(_data);
            if (this.mSelectIndex == 0) this.mDaoJUCtr.setUseSt(true)
            else if (this.mSelectIndex <= 3) this.mDaoJuCtrs[this.mSelectIndex - 1].setUseSt(true)
        }
    }

    private useItem(_data: ItemBaseData, _x: number, _y: number) {
        this.canFire = false;
        let titems = this.mSelectItems.slice();

        if (_data.isLineProp) {
            this.mIsFlying = true;
            let tangle = MathTool.getAngleByTwoPoint(this.mPaoPos.x, this.mPaoPos.y, _x, _y);
            SoundManager.playSound("lineeff.mp3");
            AnimManager.showLineImgEff(this, this.mPaoPos.x, this.mPaoPos.y, tangle, 1000, () => {
                this.mIsFlying = false;
                if (titems.length) {
                    GridManager.getIns().removeItems(titems);
                }
                GridManager.getIns().checkDropItems();
            });
        } else if (_data.isBombProp || _data.isBigBombProp) {
            this.mIsFlying = true;
            this.moveUseDaoJuItem(_data, () => {
                SoundManager.playSound("bomb.wav");
                AnimManager.show(this.itemParent, this.mDaojuImg.x - 70, this.mDaojuImg.y - 70, AnimManager.BombAnim, () => {
                    this.removeSelectItems(titems);
                    this.mIsFlying = false;
                }, 500);
            });

        } else if (_data.is3RandomDispose) {
            this.mIsFlying = true;
            this.moveUseDaoJuItem(_data, () => {
                let tarr = GridManager.getIns().find3RandomItem({});
                AnimManager.showTEff(this.itemParent, this.mDaojuImg.x, this.mDaojuImg.y, tarr, () => {
                    this.removeSelectItems(tarr);
                    this.mIsFlying = false;
                });
            })
        }
        GridManager.getIns().scoreStep++;
        GridManager.getIns().restDaojuStep();
        if (this.mSelectIndex == 0) {
            this.nextDaoju();
        } else {
            PlayerData.getIns().addItem(this.mSelectData.id + "", -1);
            this.mDaoJuCtrs[this.mSelectIndex - 1].setUseSt(false);
            this.mDaoJuCtrs[this.mSelectIndex - 1].fresh();
        }
        this.mPaoCtr.clearPropData();
        this.mSelectData = null;

    }

    private nextDaoju() {
        if (this.mIsWuJin) this.mDaoJuIndex = Math.floor(Math.random() * (this.mUnlockDaoJuIndex + 1));
        else {
            this.mDaoJuIndex++;
            if (this.mDaoJuIndex > this.mUnlockDaoJuIndex) this.mDaoJuIndex = 0;

        }
        this.mDaoJUCtr.setData(this.mdaojus[this.mDaoJuIndex]);
    }

    private canceUseDaoJu() {
        if (this.mSelectData) {
            this.mPaoCtr.clearPropData();
            if (this.mSelectIndex == 0) this.mDaoJUCtr.setUseSt(false)
            else if (this.mSelectIndex <= 3) this.mDaoJuCtrs[this.mSelectIndex - 1].setUseSt(false)
            this.mSelectData = null;
        }
    }

    private moveUseDaoJuItem(_data: ItemBaseData, _func: Function) {
        let trc = this.mlineData.rc;
        this.mDaojuImg.setData(_data);
        this.mDaojuImg.setPos(this.mFirePos.x, this.mFirePos.y);
        this.itemParent.addChild(this.mDaojuImg);
        this.mDaojuImg.moveByPath(this.mlineData.points, trc.row, trc.col, () => {
            this.mDaojuImg.removeSelf();
            _func();
        })
    }

    private mouseEnableChange(act: boolean, showMask: boolean = false) {
        this.mCanFire2 = act;
        if (showMask) {

        }
    }

    private removeSelectItems(_arr) {
        if (_arr.length) {
            GridManager.getIns().removeItems(_arr);
        }
        this.clearSelect();
        GridManager.getIns().checkDropItems();

    }

    private drawLine(_points) {
        this.lineSp.y = this.itemParent.y >= 0 ? this.itemParent.y : 0;
        this.lineSp.graphics.clear();
        this.lineSp.graphics.drawLines(0, 0, _points, "#00ff00", 4);
        // let trc=this.mlineData.rc;
        // let tp3
        // if(trc){
        //     let tp2=ItemBaseData.getPosByRC(trc.row,trc.col);
        //     tp3 = this.lineSp.globalToLocal(this.itemParent.localToGlobal(new Laya.Point(tp2.x,tp2.y)))
        //     this.lineSp.graphics.drawCircle(tp3.x,tp3.y,30,"#ff0000");
        // }
        // for(let row=0;row<GridManager.getIns().grid.row;row++){
        //     let tlen =  ItemBaseData.isSingleRow(row)?GridManager.getIns().grid.col:GridManager.getIns().grid.col-1;
        //     for(let col=0;col<tlen;col++){
        //         let tp = ItemBaseData.getPosByRC(row,col);
        //         tp3 = this.lineSp.globalToLocal(this.itemParent.localToGlobal(new Laya.Point(tp.x,tp.y)))
        //         this.lineSp.graphics.drawCircle(tp3.x,tp3.y,30,null,"#ffff00");
        //     }
        // }
    }

    private clear() {
        this.lineSp.graphics.clear();
        this.clearSelect();
    }



    private hardLvUp() {
        this.changeGameSt(4);
        GridManager.getIns().lvup();
        TipManager.ins.showMsgAlert("难度提升！", this);
        this.timerOnce(1000, this, () => {
            GridManager.getIns().initWuJinGrid();
            this.changeGameSt(1);
        });
    }

    private gameOver(_win: boolean) {
        if (this.mIsGameOver) return;
        this.mIsGameOver = true;
        this.timer.clear(this, this.update);
        Laya.timer.once(1000, this, () => {
            if (_win) {
                MyDialogManager.getIns().sceneOpen("PassDialog.scene", false);

            } else {
                MyDialogManager.getIns().sceneOpen("FailDialog.scene", false, this.mHaveRevive ? false : true);

                this.mHaveRevive = true;
            }
        });
    }


    private createLineData(_x: number, _y: number) {
        let tardata = { linePoints: [], points: [], blister: [], angle: 0, rc: null, item: null, lastPos: null, points2: [], source: null };
        let tlinedata = MathTool.getZheXianByV(this.mPaoPos.x, this.mPaoPos.y - this.lineSp.y, _x, _y, 0, 660);
        let tlinepoints = [];
        let titem: Item;
        let tp;
        let tpp: Laya.Point;
        // for(let i=0;i<ttdata.spointIndex.length;i++){
        //     tp=ttdata.point[ttdata.spointIndex[i]];
        //     tpoints.push(tp.x,tp.y);
        // }
        let ismeetBlister: boolean;
        let trc
        let tcache = {};
        let tperIsBlister: boolean;
        for (let i = 0; i < tlinedata.point.length; i++) {
            tp = tlinedata.point[i];
            tpp = this.itemParent.globalToLocal(this.lineSp.localToGlobal(tp, true));
            //tpp.x-=30;
            tperIsBlister = false;
            titem = GridManager.getIns().grid.getItemByPos(tpp.x, tpp.y);
            if (titem) {
                if (!tcache[titem.data.rcFlag]) {
                    tcache[titem.data.rcFlag] = 1;
                    if (titem.data.isBlister) {
                        tardata.blister.push(titem);
                        ismeetBlister = true;
                        trc = { row: titem.data.row, col: titem.data.col }//ItemBaseData.getRCByPos(tpp.x,tpp.y);
                        tardata.rc = trc//this.getNerstRc(tpp);
                        tperIsBlister = true;
                        continue;
                    } else {
                        tardata.item = titem;
                        break;
                    }
                }
            }
            else {
                trc = ItemBaseData.getRCByPos(tpp.x, tpp.y);
                if (trc.row < 0) break;
                if (GridManager.getIns().grid.isInLimit(trc.row, trc.col)) tardata.rc = trc//this.getNerstRc(tpp)
            }
            if (!ismeetBlister) tlinepoints.push(tp.x, tp.y);
            tardata.points.push(tpp);
        }
        tardata.linePoints = tlinepoints;
        if (!GridManager.getIns().grid.isInLimit(trc.row, trc.col)) tardata.rc = this.getNearRC(trc);
        tardata.lastPos = tpp;
        tardata.angle = tlinedata.angle;
        let tlen = tardata.points.length;
        for (let i = 0; i < tlinedata.spointIndex.length; i++) {
            if (tlinedata.spointIndex[i] >= tlen) break;
            tardata.points2.push(tardata.points[tlinedata.spointIndex[i]]);
        }
        tardata.points2.push(tardata.points[tardata.points.length - 1]);
        tardata.source = tlinedata;
        return tardata;

    }

    private getNearRC(_rc) {
        let trow = _rc.row;
        let tcol = _rc.col - 1;
        let tgrid: Grid = GridManager.getIns().grid;
        if (tgrid.isInLimit(trow, tcol) && !tgrid.getItem(trow, tcol)) return { row: trow, col: tcol };
        tcol = _rc.col + 1;
        if (tgrid.isInLimit(trow, tcol) && !tgrid.getItem(trow, tcol)) return { row: trow, col: tcol };
        tcol = _rc.col;
        trow = _rc.row - 1;
        if (tgrid.isInLimit(trow, tcol) && !tgrid.getItem(trow, tcol)) return { row: trow, col: tcol };
        tcol = ItemBaseData.isSingleRow(_rc.row) ? _rc.col - 1 : _rc.col + 1;
        if (tgrid.isInLimit(trow, tcol) && !tgrid.getItem(trow, tcol)) return { row: trow, col: tcol };
        trow = _rc.row + 1;
        tcol = _rc.col;
        if (tgrid.isInLimit(trow, tcol) && !tgrid.getItem(trow, tcol)) return { row: trow, col: tcol };
        tcol = ItemBaseData.isSingleRow(_rc.row) ? _rc.col - 1 : _rc.col + 1;
        if (tgrid.isInLimit(trow, tcol) && !tgrid.getItem(trow, tcol)) return { row: trow, col: tcol };
        return _rc;
    }

    private setSelectItems(_data: ItemBaseData, _x: number, _y: number) {
        this.clearSelect();
        if (_data.isLineProp) {
            this.mSelectItems = this.getLineNearItems2(_x, _y);
        } else if (_data.isBombProp || _data.isBigBombProp) {
            this.mSelectItems = this.getBombItems(_x, _y);
        }
        for (let i = 0; i < this.mSelectItems.length; i++) {
            this.mSelectItems[i].select = true;
        }
    }

    private getLineNearItems2(_x: number, _y: number) {
        let titems: Array<Item> = [];
        let tp1 = this.itemParent.globalToLocal(new Laya.Point(this.mPaoPos.x, this.mPaoPos.y));
        let tp2 = this.itemParent.globalToLocal(new Laya.Point(_x, _y));
        let tlineparam = MathTool.getLineMethodParam(tp1.x, tp1.y, tp2.x, tp2.y);
        let tcurrrow: number = GridManager.getIns().grid.getMaxItemRow();
        let tminRow = tcurrrow - GridManager.getIns().showRow;
        if (tminRow < 0) tminRow = 0;
        let tcollen = GridManager.getIns().grid.col;
        let titem: Item;
        for (let row = 0; row <= tcurrrow; row++) {
            for (let col = 0; col < tcollen; col++) {
                titem = GridManager.getIns().grid.getItem(row, col);
                if (titem && titem.data.isCanDispose) {
                    if (MathTool.getPointDistLine(titem.x, titem.y, tlineparam.k, tlineparam.b) <= 60) {
                        titems.push(titem);
                    }
                }
            }
        }
        return titems;
    }

    private getBombItems(_x: number, _y: number, _size: number = 2) {
        let titems: Array<Item> = [];
        //let tp= this.itemParent.globalToLocal(new Laya.Point(_x,_y));
        let trow = Math.floor(_y / ItemBaseData.WIDTH);
        let tstow = trow - _size;
        if (tstow < 0) tstow = 0;
        let terow = trow + _size;
        let titem: Item;
        let tdist: number;
        let tlen = _size * ItemBaseData.WIDTH;
        for (let row = tstow; row <= terow; row++) {
            for (let col = 0; col < GridManager.getIns().col; col++) {
                titem = GridManager.getIns().grid.getItem(row, col)
                if (titem && titem.data.isCanDispose) {
                    tdist = MathTool.getTwoPointDist(_x, _y, titem.x, titem.y);
                    if (tdist <= tlen) {
                        titems.push(titem);
                    }
                }
            }
        }
        return titems;
    }

    private getDaoJuData(_index: number) {
        let tdata: ItemBaseData = new ItemBaseData();
        if (_index == 2) tdata.setDataById(100002);
        else if (_index == 3) tdata.setDataById(100003);
        else tdata.setDataById(100001);
        return tdata;
    }

    private getRandomRCs(_num: number) {
        let tarr = [];
        let ttemp = [];

        let terow = GridManager.getIns().grid.getMaxItemRow() + 1;
        let tmaccol = GridManager.getIns().grid.col;
        let tsrow = terow - 10;
        if (tsrow < 1) tsrow = 1;

        for (let row = terow-1; row >=tsrow; row--) {
            for (let col = 0; col < tmaccol; col++) {
                if(ttemp.length>15)break;
                if (GridManager.getIns().grid.canAdd(row, col)) ttemp.push({ row: row, col: col });
            }
        }
        let tlen = Math.min(_num, ttemp.length)
        for (let i = 0; i < tlen; i++) {
            tarr.push(ttemp.splice(Math.floor(Math.random() * ttemp.length), 1)[0]);
        }
        return tarr;
    }


    private clearSelect() {
        if (this.mSelectItems) {
            for (let i = 0; i < this.mSelectItems.length; i++) {
                this.mSelectItems[i].select = false;
            }
        }
        this.mSelectItems = [];
    }

    private canClick() {
        if (!this.mCanFire2 || this.mPaoCtr.paoNum <= 0) return false;
        if (this.gameSt == 1 && !this.mIsFlying && !this.mIsGameOver) return true
        return false;
    }

    onDisable() {
        this.removeEvent();
        if (Sdk.getIns().isLongScene) {
            Sdk.getIns().hideBanner();
        }
    }
}